using System;
using System.Collections.Generic;
using System.Text;

using System.IO.Ports;

using Modbus.Data;
using Modbus.Device;
using Modbus.Utility;
using System.Threading;

namespace YangtzeFilterTestSystem
{

    public static class PLC
    {
        private static SerialPort port;

        // create modbus master
        private static IModbusSerialMaster master;

        private static byte slaveID;

        public static void Initilize()
        {
            port = new SerialPort();
            port.PortName = "COM7";
            port.BaudRate = 9600;
            port.Parity = Parity.Even;
            port.DataBits = 8;
            port.StopBits = StopBits.One;
            port.WriteTimeout = 3000;
            port.ReadTimeout = 3000;

            if (GlobalVariables.RunningMode == RUNNING_MODE.REAL)
            {
                port.Open();
            }
            else if (GlobalVariables.RunningMode == RUNNING_MODE.SIMULATION)
            {
                //DO Nothing......
            }

            master = ModbusSerialMaster.CreateRtu(port);

            slaveID = 0x07;
        }

        public static void Open(ushort valve)
        {
            ushort register = 1;
            master.WriteSingleRegister(slaveID, valve, register); 
        }

        public static void Close(ushort valve)
        {
            ushort register = 0;
            master.WriteSingleRegister(slaveID, valve, register);
        }

        public static bool MDriverControlEnable
        {
            get
            {
                ushort[] registers = new ushort[1];
                registers = master.ReadHoldingRegisters(slaveID, 0, 1);
                return Convert.ToBoolean(registers[0]);
            }

            set
            {
                master.WriteSingleRegister(slaveID, 0, Convert.ToUInt16(value));               
            }
        }

    }
}
